<template>
  <div class="publish-page">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <crumbs>{{ $route.query.id ? '编辑文章' : '发布文章' }}</crumbs>
      </div>
      <!-- 表单 -->
      <el-form ref="PublishForm" :rules="rules" :model="reqParams" label-width="80px">
        <el-form-item label="标题：" prop="title">
          <el-input v-model="reqParams.title" placeholder="请输入文章标题" style="width: 450px"></el-input>
        </el-form-item>
        <el-form-item label="内容：" prop="content">
          <quill-editor v-model="reqParams.content" @blur="onEditorBlur" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item label="封面：" prop="cover">
          <el-radio-group v-model="reqParams.cover.type" @change="reqParams.cover.images = []">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="-1">自动</el-radio>
            <el-radio :label="0">无图</el-radio>
          </el-radio-group>
          <!-- 封面组件 -->
          <div v-if="reqParams.cover.type === 1 || reqParams.cover.type === 3" >
            <cover-img
              @on-confirm="checkeCover"
              v-for="i in reqParams.cover.type"
              :key="i"
              v-model="reqParams.cover.images[i-1]">
            </cover-img>
          </div>
        </el-form-item>
        <el-form-item label="频道：" prop="channel_id">
          <!-- <channel :value="reqParams.channel_id" @input="reqParams.channel_id = $event"></channel> -->
          <channel v-model="reqParams.channel_id" @change="changeChannel"></channel>
        </el-form-item>
        <el-form-item>
          <div v-if="!$route.query.id">
            <el-button type="primary" @click="publishArticle(false)">发布文章</el-button>
            <el-button @click="publishArticle(true)">存入草稿</el-button>
          </div>
          <el-button v-else type="success" @click="BtnEditArticle">修改文章</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 引入富文本
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

// 引入文章接口
import { publishAnArticle, getArticleId, edit as editArticle } from '@/api/article'
export default {
  name: 'Publish',
  components: {
    quillEditor
  },
  data () {
    const validateType = (rule, value, callback) => {
      console.log(value)
      if (value.type === 1) {
        if (!value.images[0]) {
          return callback(new Error('请选择一张图！'))
        }
      }
      if (value.type === 3) {
        if (!(value.images[0] && value.images[1] && value.images[2])) {
          return callback(new Error('请选择三张图！'))
        }
      }
      callback()
    }
    return {
      reqParams: {
        draft: false, // 是否存为草稿（true 为草稿）
        title: null,
        content: null,
        cover: {
          type: 1,
          images: []
        },
        channel_id: null

      },
      // 富文本数据对象 || 配置富文本
      editorOption: {
        placeholder: '请输入内容',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 倾斜 下划线 删除线
            ['blockquote', 'code-block'], // 引号双引号代码块
            [{ header: 1 }, { header: 2 }], // h1 h2
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表无序列表
            [{ indent: '-1' }, { indent: '+1' }], // 向前缩进，向后缩进
            ['image'] // 图片
          ]
        }
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        channel_id: [
          { required: true, message: '请输入文章内容', trigger: 'change' }
        ],
        cover: [
          { validator: validateType, trigger: 'change' }
        ]
      }
    }
  },
  mounted () {
    // this.getArticle()
  },
  watch: {
    '$route.query.id': {
      handler () {
        console.log('user.age改变了')
        if (this.$route.query.id) {
          this.getArticle(this.$route.query.id)
        } else {
          this.$nextTick(() => {
            this.$refs.PublishForm.resetFields()
          })
        }
      },
      immediate: true // 开启深度侦听
    }
  },
  methods: {
    // 根据id获取文章 数据回填
    async getArticle (id) {
      const { data: { data } } = await getArticleId({ id })
      // console.log(data)
      this.reqParams = { ...data }
    },
    // 发布文章 根据传的参数来决定是否草稿
    publishArticle (flag) {
      this.reqParams.draft = flag
      this.$refs.PublishForm.validate(async (valid) => {
        if (valid) {
          await publishAnArticle(this.reqParams)
          this.$message.success('发布文章成功!')
          this.$router.push({ path: '/content', name: 'content' })
        }
      })
    },
    // 修改文章
    async BtnEditArticle () {
      await editArticle(this.reqParams)
      this.$message.success('编辑文章成功!')
      this.$router.push({ path: '/content', name: 'content' })
    },
    // 手动触发富文本的验证
    onEditorBlur () {
      this.$refs.PublishForm.validateField('content')
    },
    // 触发封面组件的效验
    checkeCover () {
      this.$refs.PublishForm.validateField('cover')
    },
    // 频道组件的效验
    changeChannel () {
      this.$refs.PublishForm.validateField('channel_id')
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ql-editor {
  height: 200px;
}
</style>
